package random_test;

import java.util.*;

public class Test_10_11 {


    //LCR 008. 长度最小的子数组
    public int minSubArrayLen(int target, int[] nums) {
        int left = 0, right = 0;
        int sum = 0, minLen = nums.length + 1;
        while(right < nums.length) {
            sum += nums[right];
            while(sum >= target) {
                if(right - left + 1 < minLen) minLen = right - left + 1;
                sum -= nums[left++];
            }
            right++;
        }
        if(minLen > nums.length) minLen = 0;
        return minLen;
    }

    // 18. 四数之和
    public List<List<Integer>> fourSum(int[] nums, int target) {
        List<List<Integer>> ret = new ArrayList<>();
        if(nums.length < 4) return ret;
        Arrays.sort(nums);

        for(int i = 0; i < nums.length - 3; i++) {
            // 跳过已经重复过的 i 的情况
            while(i > 0 && i < nums.length - 3 && nums[i] == nums[i-1]) i++;
            if(i == nums.length - 3) break;
            int sum1 = target - nums[i];
            for(int j = i + 1; j < nums.length - 2; j++) {
                // 跳过已经重复过的 j 的情况
                while(j > i+1 && j < nums.length-2 && nums[j] == nums[j-1]) j++;
                if(j == nums.length - 2) break;
                int left = j + 1, right = nums.length - 1;
                // 防止四数之和出现溢出的情况
                long sum2 = (long)sum1 - nums[j];
                while(left < right) {
                    if(nums[left] + nums[right] == sum2) {
                        ret.add(Arrays.asList(nums[i],nums[j],nums[left++],nums[right--]));
                        // 对 left和right 去重
                        while(left < right && nums[left] == nums[left - 1]) left++;
                        while(left < right && nums[right] == nums[right + 1]) right--;
                    }else if(nums[left] + nums[right] > sum2) {
                        right--;
                    }else {
                        left++;
                    }
                }
            }
        }
        return ret;
    }


    // 3. 无重复字符的最长子串
    public int lengthOfLongestSubstring(String ss) {
        int ret = 0;
        char[] s = ss.toCharArray();
        int[] hash = new int[128];
        int left = 0, right = 0, n = ss.length();
        while(right < n) {
            hash[s[right]]++;    // 进入窗口
            // 判断窗口中是否含有重复元素
            while(hash[s[right]] > 1) {
                // 出窗口
                hash[s[left++]]--;
            }
            ret = Math.max(ret, right - left + 1);
            right++;
        }
        return ret;
    }
}
